package com.blqy.fr.user.login;

import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blqy.fr.common.constant.RedisConstant;
import com.blqy.fr.common.execption.BlQyException;
import com.blqy.fr.common.result.ResultCodeEnum;
import com.blqy.fr.model.user.User;
import com.blqy.fr.user.mapper.UserMapper;
import com.blqy.fr.vo.user.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

//@Component 不需要写，因为这个类被LoginBean注解了，LoginBean中有@Component
@LoginBean(value = LoginType.ACCOUNT_LOGIN)
public class AccountLogin implements LoginInterface {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, Object> login(LoginAccount account) {

        if (StringUtils.isBlank(account.getUsername())){
            throw new BlQyException(ResultCodeEnum.ACCOUNT_ERROR);
        }else{
            if (!(account.getUsername().length()==11)){
                throw new BlQyException(ResultCodeEnum.ACCOUNT_ERROR);
            }
        }

        if (StringUtils.isBlank(account.getPassword())){
            throw new BlQyException(ResultCodeEnum.PASSWORD_ERROR);
        }else if (account.getPassword().length()<6){
            throw new BlQyException(ResultCodeEnum.PASSWORD_ERROR);
        }


        User username = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAcconut, account.getUsername()));
        if (username == null) {
            throw new BlQyException(ResultCodeEnum.ACCOUNT_ERROR);
        }


        User userPassword = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPassword, MD5.create().digestHex(account.getPassword())).eq(User::getAcconut, account.getUsername()));
        if (userPassword == null) {
            throw new BlQyException(ResultCodeEnum.PASSWORD_ERROR);
        }

        if (userPassword.getStatus().equals(0)){
            throw new BlQyException(ResultCodeEnum.ACCOUNT_STOP);
        }

        // 4. 生成uuid作为token保存到Redis中
        String token = UUID.randomUUID().toString();
        UserVo userVo = new UserVo();
        userVo.setAvatar(userPassword.getAvatar());
        userVo.setNickName(userPassword.getNickName());
        userVo.setId(userPassword.getId());
        account.setPassword(null);
        BeanUtils.copyProperties(account, userVo);
        redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + token, userVo, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);

        // 5.返回token
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return map;
    }

}